"""
while循环
学习目标：
1. 掌握while循环的基本语法
2. 理解while和for的区别
3. 掌握死循环的避免方法
4. 学会在实际场景中使用while循环
"""

# ==================== 1. while循环基础 ====================
print("=" * 50)
print("1. while循环基础")
print("=" * 50)

print("基本语法：")
print("""
while 条件:
    循环体
""")

# 简单示例
count = 1
print("\n打印1到5：")
while count <= 5:
    print(f"  {count}")
    count += 1  # ⚠️ 必须更新条件，否则死循环

print("\n💡 关键点：")
print("  - 条件为True时，执行循环体")
print("  - 循环体中必须改变条件，否则死循环")
print("  - 循环体要缩进")

print()

# ==================== 2. while vs for ====================
print("=" * 50)
print("2. while 和 for 的区别")
print("=" * 50)

# 使用for循环
print("for循环打印1-5：")
for i in range(1, 6):
    print(f"  {i}")

# 使用while循环
print("\nwhile循环打印1-5：")
i = 1
while i <= 6:
    print(f"  {i}")
    i += 1

print("\n💡 选择建议：")
print("  - 已知循环次数 → 用for")
print("  - 未知循环次数，根据条件判断 → 用while")
print("  - 遍历序列 → 用for")
print("  - 等待某个条件满足 → 用while")

print()

# ==================== 3. 实战：累加求和 ====================
print("=" * 50)
print("3. 实战：累加求和")
print("=" * 50)

# 计算1到100的和
total = 0
num = 1
while num <= 100:
    total += num
    num += 1

print(f"1 + 2 + ... + 100 = {total}")

print()

# ==================== 4. 实战：用户输入验证 ====================
print("=" * 50)
print("4. 实战：密码验证（模拟）")
print("=" * 50)

correct_password = "123456"
max_attempts = 3
attempts = 0

print("密码验证系统")
print(f"您有{max_attempts}次机会")
print()

# 模拟用户输入（实际应用中用input()）
inputs = ["111", "222", "123456"]  # 模拟输入序列
input_index = 0

while attempts < max_attempts:
    # 模拟获取用户输入
    password = inputs[input_index]
    input_index += 1
    attempts += 1
    
    print(f"第{attempts}次尝试：输入密码 {'*' * len(password)}")
    
    if password == correct_password:
        print("✅ 密码正确！登录成功")
        break
    else:
        remaining = max_attempts - attempts
        if remaining > 0:
            print(f"❌ 密码错误，还有{remaining}次机会")
        else:
            print("❌ 密码错误，账户已锁定")

print()

# ==================== 5. 实战：猜数字游戏 ====================
print("=" * 50)
print("5. 实战：猜数字游戏（模拟）")
print("=" * 50)

import random
secret_number = random.randint(1, 100)
guess_count = 0
max_guess = 7

print(f"我想了一个1-100之间的数字")
print(f"你有{max_guess}次机会猜")
print()

# 模拟猜测序列
guesses = [50, 75, 88, 94, 97, 99, 100]
guess_index = 0

while guess_count < max_guess:
    # 模拟用户输入
    if guess_index < len(guesses):
        guess = guesses[guess_index]
    else:
        guess = secret_number
    guess_index += 1
    guess_count += 1
    
    print(f"第{guess_count}次猜测：{guess}")
    
    if guess == secret_number:
        print(f"🎉 恭喜！猜对了！答案是{secret_number}")
        print(f"你用了{guess_count}次猜中")
        break
    elif guess < secret_number:
        print("太小了！")
    else:
        print("太大了！")
    
    if guess_count >= max_guess:
        print(f"😢 机会用完了！答案是{secret_number}")

print()

# ==================== 6. 实战：倒计时 ====================
print("=" * 50)
print("6. 实战：倒计时")
print("=" * 50)

seconds = 5
print("倒计时开始：")
while seconds > 0:
    print(f"  {seconds}秒...")
    seconds -= 1
print("  时间到！")

print()

# ==================== 7. 实战：找出第一个大于100的平方数 ====================
print("=" * 50)
print("7. 实战：找出第一个平方数大于100的数")
print("=" * 50)

num = 1
while num ** 2 <= 100:
    num += 1

print(f"第一个平方数大于100的数是：{num}")
print(f"{num}² = {num ** 2}")

print()

# ==================== 8. 实战：计算数字位数 ====================
print("=" * 50)
print("8. 实战：计算数字的位数")
print("=" * 50)

number = 12345
temp = number
digit_count = 0

while temp > 0:
    temp //= 10
    digit_count += 1

print(f"数字{number}有{digit_count}位")

print()

# ==================== 9. 实战：反转数字 ====================
print("=" * 50)
print("9. 实战：反转数字")
print("=" * 50)

number = 12345
reversed_num = 0

print(f"原数字：{number}")

temp = number
while temp > 0:
    digit = temp % 10  # 获取最后一位
    reversed_num = reversed_num * 10 + digit
    temp //= 10

print(f"反转后：{reversed_num}")

print()

# ==================== 10. 实战：求最大公约数（辗转相除法） ====================
print("=" * 50)
print("10. 实战：求最大公约数")
print("=" * 50)

a = 48
b = 18

print(f"求{a}和{b}的最大公约数")
print()

original_a = a
original_b = b

while b != 0:
    remainder = a % b
    print(f"{a} ÷ {b} = {a//b} ... {remainder}")
    a = b
    b = remainder

print(f"\n{original_a}和{original_b}的最大公约数是：{a}")

print()

# ==================== 11. 实战：菜单循环 ====================
print("=" * 50)
print("11. 实战：简单菜单系统（模拟）")
print("=" * 50)

# 模拟用户选择
choices = ["1", "2", "3", "4", "4"]
choice_index = 0

while True:
    print("\n===== 菜单 =====")
    print("1. 查看信息")
    print("2. 添加信息")
    print("3. 删除信息")
    print("4. 退出")
    print("================")
    
    # 模拟输入
    if choice_index < len(choices):
        choice = choices[choice_index]
    else:
        choice = "4"
    choice_index += 1
    
    print(f"选择：{choice}")
    
    if choice == "1":
        print("→ 查看信息功能")
    elif choice == "2":
        print("→ 添加信息功能")
    elif choice == "3":
        print("→ 删除信息功能")
    elif choice == "4":
        print("→ 退出系统")
        break
    else:
        print("→ 无效选择")

print()

# ==================== 12. 实战：求和直到超过目标 ====================
print("=" * 50)
print("12. 实战：累加到超过目标值")
print("=" * 50)

target = 100
total = 0
num = 1

print(f"目标值：{target}")
print("累加过程：")

while total < target:
    total += num
    print(f"  {num}: 累计 = {total}")
    num += 1

print(f"\n需要加到{num-1}才能超过{target}")
print(f"总和：{total}")

print()

# ==================== 13. 实战：斐波那契数列 ====================
print("=" * 50)
print("13. 实战：生成斐波那契数列")
print("=" * 50)

max_value = 100
a, b = 0, 1

print(f"小于{max_value}的斐波那契数列：")
fib_list = []

while a < max_value:
    fib_list.append(a)
    a, b = b, a + b

print(fib_list)

print()

# ==================== 14. 实战：数字求和（各位相加） ====================
print("=" * 50)
print("14. 实战：求数字各位数字之和")
print("=" * 50)

number = 12345
total = 0
temp = number

print(f"数字：{number}")

while temp > 0:
    digit = temp % 10
    total += digit
    temp //= 10

print(f"各位数字之和：{total}")

print()

# ==================== 15. 实战：判断回文数 ====================
print("=" * 50)
print("15. 实战：判断回文数")
print("=" * 50)

number = 12321
original = number
reversed_num = 0

# 反转数字
temp = number
while temp > 0:
    digit = temp % 10
    reversed_num = reversed_num * 10 + digit
    temp //= 10

print(f"原数字：{original}")
print(f"反转后：{reversed_num}")

if original == reversed_num:
    print(f"✅ {original}是回文数")
else:
    print(f"❌ {original}不是回文数")

print()

# ==================== 16. while True 模式 ====================
print("=" * 50)
print("16. while True 无限循环模式")
print("=" * 50)

print("示例：处理数据直到遇到特定条件")

data_list = [10, 20, 30, -1, 40, 50]  # -1是终止标志
index = 0
total = 0

while True:
    if index >= len(data_list):
        break
    
    data = data_list[index]
    index += 1
    
    if data == -1:
        print("遇到终止标志，停止处理")
        break
    
    total += data
    print(f"  处理数据：{data}，累计：{total}")

print(f"总和：{total}")

print()

# ==================== 死循环警告 ====================
print("=" * 50)
print("⚠️ 避免死循环")
print("=" * 50)

print("""
死循环示例（注释掉，避免真的死循环）：

# 错误示例1：忘记更新条件
# count = 1
# while count <= 5:
#     print(count)
#     # 忘记 count += 1，导致死循环

# 错误示例2：条件永远为True
# while True:
#     print("无限循环")
#     # 没有break，导致死循环

正确做法：
1. 确保循环变量会改变
2. 确保条件最终会变False
3. while True必须有break
4. 设置最大循环次数作为保险
""")

print()

# ==================== 总结 ====================
print("=" * 50)
print("✨ while循环总结")
print("=" * 50)
print("""
1. 基本语法：
   while 条件:
       循环体

2. 执行流程：
   ✅ 判断条件
   ✅ 条件为True，执行循环体
   ✅ 重复上述步骤
   ✅ 条件为False，退出循环

3. while vs for：
   - while：不知道循环次数，根据条件
   - for：已知循环次数或遍历序列

4. 常见模式：
   - while 条件: ...      条件循环
   - while True: ... break  无限循环+break

5. 常见应用：
   - 用户输入验证
   - 菜单系统
   - 等待条件满足
   - 数学计算（求最大公约数等）
   - 游戏主循环

6. 注意事项：
   ⚠️ 必须更新循环条件，避免死循环
   ⚠️ while True 必须有break
   ⚠️ 复杂条件可以先计算再判断
   ⚠️ 可以设置最大循环次数作为保险
""")
print("=" * 50)

